package com.itx77.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itx77.dao.AppInfoDao;
import com.itx77.dao.AppVersionDao;
import com.itx77.entity.AppInfo;
import com.itx77.entity.AppVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * @author: .x77
 * @CreateTime:2023/12/7 15:17
 */
@Service
public class AppInfoService {
    @Autowired
    AppInfoDao appInfoDao;
    @Autowired
    AppVersionDao appVersionDao;

    public PageInfo getPage(AppInfo appInfo, Integer pageNum) {
        PageHelper.startPage(pageNum,10, "id desc");
        List<AppInfo> appInfos = appInfoDao.queryAllByLimit(appInfo);
        PageInfo<AppInfo> page = new PageInfo<>(appInfos);
        return page;
    }

    public void appUpload(AppInfo appInfo) {
        if (appInfo.getId() == null){
            appInfoDao.insert(appInfo);
        }else {
            appInfoDao.update(appInfo);
        }
    }

    public AppInfo selById(Long id) {
        return appInfoDao.queryById(id);
    }

    public Boolean selByApk(AppInfo appInfo) {
        if (appInfo.getId() != null){
            if (appInfo.getApkname().equals(appInfoDao.selByApkName(appInfo))){
                return true;
            }
        }
        int i = appInfoDao.selByCount(appInfo);
        if (i>0){
            return false;
        }else {
            return true;
        }
    }

    public boolean delById(Long id,HttpServletRequest request) {
        AppInfo appInfo = appInfoDao.queryById(id);

        int i = appInfoDao.deleteById(id);
        if (i>0){
            new File(appInfo.getLogopicpath()).delete();
            AppVersion appVersion = appVersionDao.queryById(id);
//            String realPath = request.getServletContext().getRealPath(appVersion.getDownloadlink());
//            File file = new File(realPath);
//            if (!file.exists()){
//                file.delete();
//            }
//            appVersionDao.deleteById(id);
            return true;
        }
        return false;
    }

    public void updStatus(AppInfo appInfo) {
        appInfoDao.update(appInfo);
    }

    public void updByXiu(Long id) {
        AppInfo app = appInfoDao.queryById(id);
        if (app.getStatus() == 4){
            app.setStatus(5L);
        }else if (app.getStatus() == 5){
            app.setStatus(4L);
        }
        appInfoDao.update(app);
    }
}
